package com.football.springboot.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.football.springboot.common.Constants;
import com.football.springboot.entity.*;
import com.football.springboot.mapper.FormationMapper;
import com.football.springboot.service.*;
import com.football.springboot.vo.TeamQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.football.springboot.common.Return;
import com.football.springboot.common.Result;
//导入service
//导入entity

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 李越
 * @since 2023-02-18
 */
@Api(tags = "球队管理")
@RestController
@RequestMapping("/team")
public class TeamController {

    @Resource
    private ITeamService teamService;

    @Resource
    private ILeagueService leagueService;

    @Resource
    private FormationMapper formationMapper;

    @Resource
    private ITeamAbilityService teamAbilityService;

    @Resource
    private IPlayerService playerService;

    @Resource
    private ITeamDataService teamDataService;

    @Resource
    private IGameService gameService;

    @Resource
    private IGameDataService gameDataService;

    @Resource
    private ITeamDataSingleService teamDataSingleService;

    // 新增或者更新
    @ApiOperation("新增或者更新")
    @PostMapping("/saveOrUpdate")
    public Result save(@RequestBody Team team) {
        teamService.saveOrUpdate(team);
        return Result.success();
    }


    //删除
    @ApiOperation("删除")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        teamService.removeById(id);
        return Result.success();
    }

    //批量删除
    @ApiOperation("批量删除")
    @PostMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        teamService.removeByIds(ids);
        return Result.success();
    }

    //查询全部
    @ApiOperation("查询全部")
    @GetMapping("/findall")
    public Result findAll() {
        return Result.success(teamService.list());
    }

    //根据id查找
    @ApiOperation("根据id查找")
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(teamService.getById(id));
    }

    //分页查询
    @ApiOperation("分页查询")
    @GetMapping("/pageTeam")
    public Return pageTeam(@RequestParam Integer current,
                           @RequestParam Integer limit,
                           TeamQueryVo teamQueryVo) {

        //创建page对象,传递当前页数current,每页记录数limit
        Page<Team> page = new Page<>(current,limit);
        //构建条件 模糊查询
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();

        String teamName = teamQueryVo.getTeamName();
        Integer league = teamQueryVo.getLeague();

        //比赛名称查询
        if(!StringUtils.isEmpty(teamName)){
            queryWrapper.like("team_name",teamName);
        }


        //根据联赛名称(id)查询
        if(league!=null){
            //查出该联赛的球队id列表
            List<Integer> teamIds = leagueService.getLeagueTeam(league);
            queryWrapper.in(CollectionUtils.isNotEmpty(teamIds),"id",teamIds);
            //查询不到球队时,返回空数据
            if (CollectionUtils.isEmpty(teamIds)){
                Page<Team> page1 = new Page<>();
                return Return.ok().put("pageTeam",page1).put("total",0);
            }
        }

        queryWrapper.orderByDesc("id");
        Page<Team> pageTeam = teamService.page(page,queryWrapper);

        return Return.ok().put("pageTeam",pageTeam).put("total",pageTeam.getTotal());
    }

    //查看球队参加的联赛id
    @ApiOperation("查看球队参加的联赛id")
    @GetMapping("/leagueTeam/{teamId}")
    public Result getLeagueTeam(@PathVariable Integer teamId){
        return Result.success(teamService.getLeagueTeam(teamId));
    }

    //查看球队参加的联赛
    @ApiOperation("查看球队参加的联赛")
    @GetMapping("/findleaguelist/{teamId}")
    public Result findleaguelist(@PathVariable Integer teamId){
        return Result.success(teamService.getLeagueByTeamId(teamId));
    }

    //获取所有球队阵型图的值
    @ApiOperation("获取所有球队阵型图的值")
    @GetMapping("/formation")
    public Result getFormation(){
        QueryWrapper<Formation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", Constants.FORMATION_TYPE);
        return Result.success(formationMapper.selectList(queryWrapper));
    }

    //获取球队能力值
    @ApiOperation("获取球队能力值")
    @GetMapping("/getTeamAbility")
    public Result getTeamAbility(@RequestParam Integer teamId){

        return Result.success(teamService.getTeamAbility(teamId));
    }

    //编辑球队能力值
    @ApiOperation("编辑球队能力值")
    @PostMapping("/saveAbility")
    public Result saveAbility(@RequestBody TeamAbility teamAbility,
                              @RequestParam Integer teamId){
        //把teamId关联给球队能力表的team_id
        teamAbility.setTeamId(teamId);
        System.out.println(teamAbility);
        UpdateWrapper<TeamAbility> updateWrapper = new UpdateWrapper<>();

        QueryWrapper<TeamAbility> queryWrapper = new QueryWrapper<>();
        if (teamAbilityService.getOne(queryWrapper.eq("team_id",teamAbility.getTeamId()))==null){
            return Result.success(teamAbilityService.save(teamAbility));
        }else{
            return Result.success(teamAbilityService.update(teamAbility,updateWrapper.eq("team_id",teamId)));
        }

    }

    //查看球队阵容
    @ApiOperation("查看球队阵容")
    @GetMapping("/getTeamPlayerList")
    public Result getTeamPlayerList(@RequestParam Integer teamId){
        return Result.success(teamService.getTeamPlayers(teamId));
    }



    //导出球队接口
    @ApiOperation("导出球队接口")
    @GetMapping(value = "/export")
    public void export(HttpServletResponse response) throws Exception{
        //从数据库中查询出所有球队数据
        List<Team> list = teamService.list();
        //写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        //自定义标题名
        writer.addHeaderAlias("teamName","球队名称");
        writer.addHeaderAlias("teamImg","球队图片");
        writer.addHeaderAlias("teamCoach","球队教练");
        writer.addHeaderAlias("teamProfile","球队简介");
        writer.addHeaderAlias("teamHome","主场球场");
        writer.addHeaderAlias("teamCreate","球队成立时间");

        //一次性写出list内的对象到excel,使用默认样式，强制输出标题
        writer.write(list,true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("球队信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }
    //导入球队接口
    @ApiOperation("导入球队接口")
    @RequestMapping(value = "/import",method = RequestMethod.POST)
    public Return imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);

        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<Team> teams = CollUtil.newArrayList();
        for (List<Object> row : list) {
            Team team = new Team();
            team.setTeamName(row.get(1).toString());
            team.setTeamImg(row.get(2).toString());
            team.setTeamCoach(row.get(3).toString());
            team.setTeamProfile(row.get(4).toString());
            team.setTeamHome(row.get(5).toString());
            String create = row.get(6).toString();
            Date date =  new SimpleDateFormat("yyyy-MM-dd").parse(create);
            team.setTeamCreate(date);
            teams.add(team);
        }

        teamService.saveBatch(teams);
        return Return.ok();
    }


    //前台查询球队资料
    @ApiOperation("前台查询球队资料")
    @RequestMapping(value = "/front/getteambyleagueId",method = RequestMethod.GET)
    public Result getteambyleagueId(@RequestParam Integer leagueId,
                                    @RequestParam String teamName){
        List<Integer> teamids = leagueService.getLeagueTeam(leagueId);
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(!teamids.isEmpty(),"id",teamids);
        queryWrapper.like(!StringUtils.isEmpty(teamName),"team_name",teamName);
        List<Team> teams = teamService.list(queryWrapper);
        return  Result.success(teams);
    }

    //前台查看单个球队详细资料(包括球队能力 球队阵容)
    @ApiOperation("前台查看单个球队详细资料")
    @GetMapping("/front/getteambyid")
    public Result getteambyid(@RequestParam Integer teamId) {
        //球队信息
        Team team=teamService.getById(teamId);
        //球队能力
        QueryWrapper<TeamAbility> queryWrapperta = new QueryWrapper<>();
        queryWrapperta.eq(teamId!=null,"team_id",teamId);
        team.setTeamAbility(teamAbilityService.getOne(queryWrapperta));
        //球队阵容
        QueryWrapper<Player> queryWrapperp = new QueryWrapper<>();
        queryWrapperp.eq(teamId!=null,"team_id",teamId);
        List<Player> players = playerService.list(queryWrapperp);
        team.setPlayers(players);
        //球队参加联赛
        List<League> leagues = teamService.getLeagueByTeamId(team.getId());
        team.setLeagueList(leagues);
        return Result.success(team);
    }

    //前台查看单个球队不同联赛的赛季数据 （包括全部联赛的总计）
    @ApiOperation("前台查看单个球队不同联赛的赛季数据")
    @GetMapping("/front/getteamdata")
    public Result getteamdata(@RequestParam Integer teamId, @RequestParam Integer leagueId, @RequestParam String homeAway){
        TeamData teamData = new TeamData();
        System.err.println("初始化："+teamData);
        if (homeAway.equals("主场")){
            if (leagueId!=null){//查询一支球队一个联赛主场数据
                System.err.println("查询主场单联赛：");
                QueryWrapper<TeamData> queryWrappertd = new QueryWrapper<>();
                queryWrappertd.eq(teamId!=null,"team_id",teamId);
                queryWrappertd.eq("league_id",leagueId);
                queryWrappertd.like("home_away","主场");
                teamData=teamDataService.getOne(queryWrappertd);
                System.err.println(teamId+" "+leagueId+" "+"单联赛主场数据："+teamData);
                //找的到再返回
                if (!ObjectUtils.isEmpty(teamData)){
                    teamData.setTeam(teamService.getById(teamId));
                    teamDataService.countleague(teamData);
                    return Result.success(teamData);
                }else{
                    return Result.success(teamData);
                }
            }else{//查询一支球队所有联赛的总主场数据
                //先查出一支球队参加了哪些联赛 也可以使用querywrapper
                System.err.println("查询主场所有联赛");
                QueryWrapper<TeamData> queryWrappertds = new QueryWrapper<>();
                queryWrappertds.eq("team_id",teamId);
                queryWrappertds.eq("home_away","主场");

                List<TeamData> hometeamDataList=teamDataService.list(queryWrappertds);
                TeamData hometeamDataall=new TeamData();
                hometeamDataall=teamDataService.teamDataallleague(hometeamDataList,hometeamDataall);
                teamDataService.countleague(hometeamDataall);
                System.err.println(hometeamDataall);
                return Result.success(hometeamDataall);
            }
        }
        if(homeAway.equals("客场")){
            if (leagueId!=null){//查询一支球队一个联赛客场数据
                System.err.println("查询客场单联赛：");
                QueryWrapper<TeamData> queryWrappertd = new QueryWrapper<>();
                queryWrappertd.eq(teamId!=null,"team_id",teamId);
                queryWrappertd.eq("league_id",leagueId);
                queryWrappertd.like("home_away","客场");
                teamData=teamDataService.getOne(queryWrappertd);
                //找得到再返回
                if (!ObjectUtils.isEmpty(teamData)){
                    teamData.setTeam(teamService.getById(teamId));
                    teamDataService.countleague(teamData);
                    return Result.success(teamData);
                }else{
                    return Result.success(teamData);
                }
            }else{//查询一支球队所有联赛的总客场数据
                System.err.println("查询客场所有联赛");
                QueryWrapper<TeamData> queryWrappertds = new QueryWrapper<>();
                queryWrappertds.eq("team_id",teamId);
                queryWrappertds.eq("home_away","客场");
                List<TeamData> awayteamDataList=teamDataService.list(queryWrappertds);
                TeamData awayteamDataall=new TeamData();
                awayteamDataall=teamDataService.teamDataallleague(awayteamDataList,awayteamDataall);
                teamDataService.countleague(awayteamDataall);
                System.err.println(awayteamDataall);
                return Result.success(awayteamDataall);
            }

        }
        if (homeAway.equals("全部") || homeAway.equals("")){
            if (leagueId!=null){//查询一支球队一个联赛的总数据
                TeamData hometeamdata=teamDataService.getupdategamedata(teamId,leagueId,"主场");
                TeamData awayteamdata = teamDataService.getupdategamedata(teamId,leagueId,"客场");
                //判断主客场数据存在的情况
                if (!ObjectUtils.isEmpty(awayteamdata) && !ObjectUtils.isEmpty(hometeamdata)) {//主客场都存在
                    //主客场数据执行相加
                    teamData = teamDataService.teamDataall(hometeamdata,awayteamdata);
                    teamData.setTeam(teamService.getById(teamId));
                    teamDataService.countleague(teamData);
                    return Result.success(teamData);
                }else if (!ObjectUtils.isEmpty(hometeamdata) && ObjectUtils.isEmpty(awayteamdata)){//只有主场数据
                    hometeamdata.setTeam(teamService.getById(teamId));
                    teamDataService.countleague(hometeamdata);
                    return Result.success(hometeamdata);
                }else if (!ObjectUtils.isEmpty(awayteamdata) && ObjectUtils.isEmpty(hometeamdata)){//只有客场数据
                    awayteamdata.setTeam(teamService.getById(teamId));
                    teamDataService.countleague(awayteamdata);
                    return Result.success(awayteamdata);
                }
            }else{//查询一支球队所有联赛的总数据
                System.err.println("查询所有联赛数据");
                QueryWrapper<TeamData> queryWrappertds = new QueryWrapper<>();
                queryWrappertds.eq("team_id",teamId);
                List<TeamData> teamDataList=teamDataService.list(queryWrappertds);
                TeamData teamDataall=new TeamData();
                teamDataall=teamDataService.teamDataallleague(teamDataList,teamDataall);
                teamDataService.countleague(teamDataall);
                System.err.println(teamDataall);
                return Result.success(teamDataall);
            }
        }


        return Result.success(teamData);
    }


    //前台球队详情页面查看球队赛程（包括单场比赛的详细信息）
    @ApiOperation("前台球队详情页面查看球队赛程")
    @GetMapping("/front/getteamgame")
    public Result getteamgame(@RequestParam Integer teamId,@RequestParam Integer leagueId,@RequestParam String homeAway){
        QueryWrapper<Game> queryWrapperg = new QueryWrapper<>();
        queryWrapperg.eq(leagueId!=null,"league_id",leagueId);
        queryWrapperg.orderByDesc("game_time");

        List<Game> homegameList = new ArrayList<>();
        List<Game> awaygameList = new ArrayList<>();
        List<Game> gameListall = new ArrayList<>();

        //主场比赛赛程
        if (homeAway.equals("主场")){
            System.err.println("查询主场");
            queryWrapperg.eq(teamId!=null,"home_team",teamId);
            gameListall=gameService.list(queryWrapperg);
            gameListall.forEach(game -> {
                QueryWrapper<TeamDataSingle> queryWrappertds = new QueryWrapper<>();
                QueryWrapper<GameData> queryWrappergd = new QueryWrapper<>();
                queryWrappergd.eq(game.getId()!=null,"game_id",game.getId());
                game.setGameData(gameDataService.getOne(queryWrappergd));
                game.setLeague(leagueService.getById(game.getLeagueId()));
                game.setHometeaminfo(teamService.getById(game.getHomeTeam()));
                game.setAwayteaminfo(teamService.getById(game.getAwayTeam()));
                queryWrappertds.eq(game.getId()!=null,"game_id",game.getId());
                queryWrappertds.eq(game.getHomeTeam()!=null,"team_id",game.getHomeTeam());
                game.setTeamDataSingle(teamDataSingleService.getOne(queryWrappertds));
            });
            return Result.success(gameListall);
        }
        //客场比赛赛程
        else if (homeAway.equals("客场")){
            System.err.println("查询客场");
            queryWrapperg.eq(teamId!=null,"away_team",teamId);
            gameListall=gameService.list(queryWrapperg);
            gameListall.forEach(game -> {
                QueryWrapper<TeamDataSingle> queryWrappertds = new QueryWrapper<>();
                QueryWrapper<GameData> queryWrappergd = new QueryWrapper<>();
                queryWrappergd.eq(game.getId()!=null,"game_id",game.getId());
                game.setGameData(gameDataService.getOne(queryWrappergd));
                game.setLeague(leagueService.getById(game.getLeagueId()));
                game.setHometeaminfo(teamService.getById(game.getHomeTeam()));
                game.setAwayteaminfo(teamService.getById(game.getAwayTeam()));
                queryWrappertds.eq(game.getId()!=null,"game_id",game.getId());
                queryWrappertds.eq(game.getAwayTeam()!=null,"team_id",game.getAwayTeam());
                game.setTeamDataSingle(teamDataSingleService.getOne(queryWrappertds));
            });
            return  Result.success(gameListall);
        }
        //全部赛程
        else if (homeAway.equals("全部")||(homeAway.equals(""))){
            System.err.println("查询全部");
            QueryWrapper<Game> queryWrapperhome = new QueryWrapper<>();
            QueryWrapper<Game> queryWrapperaway = new QueryWrapper<>();
            queryWrapperhome.eq(teamId!=null,"home_team",teamId);
            queryWrapperaway.eq(teamId!=null,"away_team",teamId);
            queryWrapperhome.eq(leagueId!=null,"league_id",leagueId);
            queryWrapperaway.eq(leagueId!=null,"league_id",leagueId);
            homegameList=gameService.list(queryWrapperhome);
            awaygameList=gameService.list(queryWrapperaway);
            gameListall.addAll(homegameList);
            gameListall.addAll(awaygameList);
            System.err.println(gameListall);
            gameListall.forEach(game -> {
                QueryWrapper<TeamDataSingle> queryWrappertds = new QueryWrapper<>();
                QueryWrapper<GameData> queryWrappergd = new QueryWrapper<>();
                queryWrappergd.eq(game.getId()!=null,"game_id",game.getId());
                game.setGameData(gameDataService.getOne(queryWrappergd));
                game.setLeague(leagueService.getById(game.getLeagueId()));
                game.setHometeaminfo(teamService.getById(game.getHomeTeam()));
                game.setAwayteaminfo(teamService.getById(game.getAwayTeam()));
                queryWrappertds.eq(game.getId()!=null,"game_id",game.getId());
                queryWrappertds.eq(teamId!=null,"team_id",teamId);
                game.setTeamDataSingle(teamDataSingleService.getOne(queryWrappertds));
                System.err.println(game.getId());
                System.err.println(teamId);
                System.err.println(game.getGameData());
                System.err.println(game.getTeamDataSingle());
            });
            gameListall.sort(Comparator.comparing(Game::getGameTime).reversed());
            return Result.success(gameListall);
        }

        return Result.success(gameListall);
    }

}

